package com.df.common;

import com.df.demo.MsgHandlers;
import io.netty.util.AttributeKey;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

public class MapThread extends Thread{

    public static AttributeKey<String> uidKey = AttributeKey.newInstance("uid");
    private static MapThread instance = new MapThread();
    private MapThread(){}
    public static MapThread getInstance(){
        return instance;
    }

    public ConcurrentHashMap<String,Player> players = new ConcurrentHashMap<>();
    public long lastUpdateTime = 0;
    public volatile boolean running = false;
    LinkedBlockingQueue<MsgWrapper> msgQue = new LinkedBlockingQueue<MsgWrapper>();
    @Override
    public void run() {
        running = true;
        if(lastUpdateTime == 0){
            lastUpdateTime = System.currentTimeMillis();
        }
        while(running){
            long now = System.currentTimeMillis();
            if(now - lastUpdateTime >= 50){
                try {
                    lastUpdateTime = now;
                    update();
                    long end = System.currentTimeMillis();
                    if(end - lastUpdateTime >= 50){
                        System.out.println("一帧执行事件超过50ms!");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public void addMsg(MsgWrapper msg){
        msgQue.offer(msg);
    }

    public void update(){
        //遍历所有玩家处理消息
        handlePlayerMsgs();

        playersMove();
    }

    private void handlePlayerMsgs() {
        int size = msgQue.size();
        while(size > 0){
            MsgWrapper msg = msgQue.poll();
            if(msg == null){
                break;
            }
            MsgHandlers.getInstance().dispatch(msg.channel,msg.msg);
        }
    }

    private void playersMove() {
        Collection<Player> players = MapThread.instance.players.values();
        for (Player player : players) {
            playerMove(player);
        }
    }

    private void playerMove(Player player) {
        List<Point> points = player.points;
        if(points.isEmpty()){
            return;
        }
        Point point = points.get(0);
        if(player.pos.distance(point) <0.05f){

        }
    }
}
